package com.slashvision.im.tool

import android.content.ContentUris
import android.content.Context
import android.content.Intent
import android.database.Cursor
import android.graphics.BitmapFactory
import android.media.MediaScannerConnection
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.DocumentsContract
import android.provider.MediaStore
import androidx.core.content.FileProvider
import com.slashvision.im.ContextUtil
import com.slashvision.im.R
import com.slashvision.im.SLog
import java.io.File


const val LOC_IMG = "_LOC_IMG_"

object StorgeUtil {


    /**
     * 保存图片的文件夹
     */

    /*val appPicDir = File(
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {
            Environment.DIRECTORY_PICTURES
        } else {
            Environment.getExternalStorageDirectory().absolutePath + File.separator + Environment.DIRECTORY_DCIM + "/Stylist"
        }
    ).apply {
        if (!exists()) {
            mkdirs()
        }
    }*/
    /*val appPicDir = if(Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {
        ContextUtil.getContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES)!!
    } else {
        File("${Environment.getExternalStorageDirectory().absolutePath}${File.separator}${Environment.DIRECTORY_PICTURES}${File.separator}${ContextUtil.getContext().resources.getString(R.string.app_name)}")
    }.apply {
        if (!exists()) {
            mkdirs()
        }
    }*/

    val appPicDir =
        File(
            "${Environment.getExternalStorageDirectory().absolutePath}${File.separator}${Environment.DIRECTORY_PICTURES}${File.separator}${
                ContextUtil.getContext().resources.getString(
                    R.string.app_name
                )
            }"
        ).apply {
            if (!exists()) {
                mkdirs()
            }
        }

    val videoCacheDir =
        File("${ContextUtil.getContext().cacheDir.absolutePath}${File.separator}video${File.separator}").apply {
            if (!exists()) {
                mkdirs()
            }
        }

    val pictureCacheDir =
        File("${ContextUtil.getContext().cacheDir.absolutePath}${File.separator}pic${File.separator}").apply {
            if (!exists()) {
                mkdirs()
            }
        }

    val voiceCacheDir =
        File("${ContextUtil.getContext().cacheDir.absolutePath}${File.separator}voice${File.separator}").apply {
            if (!exists()) {
                mkdirs()
            }
        }

    /**
     * 通知android媒体库更新文件夹
     *
     * @param filePath ilePath 文件绝对路径，、/sda/aaa/jjj.jpg
     */
    fun scanFile(context: Context?, filePath: String) {
        SLog.d(LOC_IMG, "file path: $filePath")
        try {
            val intent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE)
            val uri = getUriFromFile(File(filePath))
            intent.data = uri
            SLog.d(LOC_IMG, "file uri n: ${getUriFromFile(File(filePath))}")

            ContextUtil.getContext().sendBroadcast(intent)
            MediaScannerConnection.scanFile(
                context, arrayOf(filePath), null
            ) { path, uri ->
                SLog.i("TAG", "Scanned $path:")
                SLog.i("TAG", "-> uri=$uri")
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    fun getPicOptions(pathName: String?): IntArray {
        val ret = intArrayOf(1080, 1920)
        try {
            val options: BitmapFactory.Options = BitmapFactory.Options()
            val bp = BitmapFactory.decodeFile(pathName, options)
            //获取图片的宽高
            val height: Int = options.outHeight
            val width: Int = options.outWidth
            bp?.takeIf { !it.isRecycled }?.recycle()
            ret[0] = width
            ret[1] = height
        } catch (e: Throwable) {

        }
        return ret
    }


    fun getUriFromFile(file: File) = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        FileProvider.getUriForFile(
            ContextUtil.getContext(),
            "com.slashvision.stylist.provider",
            file
        )
    } else {
        Uri.fromFile(file)
    }


    fun getPathFromUri(context: Context, uri: Uri): String? {
        val isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                val docId: String = DocumentsContract.getDocumentId(uri)
                val split = docId.split(":").toTypedArray()
                val type = split[0]
                if ("primary".equals(type, ignoreCase = true)) {
                    return Environment.getExternalStorageDirectory().toString() + "/" + split[1]
                }

                // TODO handle non-primary volumes
            } else if (isDownloadsDocument(uri)) {
                val id: String = DocumentsContract.getDocumentId(uri)
                val contentUri: Uri = ContentUris.withAppendedId(
                    Uri.parse("content://downloads/public_downloads"), java.lang.Long.valueOf(id)
                )
                return getDataColumn(context, contentUri, null, null)
            } else if (isMediaDocument(uri)) {
                val docId: String = DocumentsContract.getDocumentId(uri)
                val split = docId.split(":").toTypedArray()
                val type = split[0]
                var contentUri: Uri? = null
                if ("image" == type) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
                } else if ("video" == type) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI
                } else if ("audio" == type) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
                }

                val selection = "_id=?"
                val selectionArgs = arrayOf(
                    split[1]
                )
                return getDataColumn(context, contentUri!!, selection, selectionArgs)
            }
        } else if ("content".equals(uri.getScheme(), ignoreCase = true)) {

            // Return the remote address
            return if (isGooglePhotosUri(uri)) uri.getLastPathSegment() else getDataColumn(
                context,
                uri,
                null,
                null
            )
        } else if ("file".equals(uri.getScheme(), ignoreCase = true)) {
            return uri.getPath()
        }
        return null
    }

    private fun getDataColumn(
        context: Context, uri: Uri, selection: String?,
        selectionArgs: Array<String>?
    ): String? {
        var cursor: Cursor? = null
        val column = "_data"
        val projection = arrayOf(
            column
        )
        try {
            cursor = context.contentResolver.query(
                uri, projection, selection, selectionArgs,
                null
            )
            if (cursor != null && cursor.moveToFirst()) {
                val index: Int = cursor.getColumnIndexOrThrow(column)
                return cursor.getString(index)
            }
        } finally {
            if (cursor != null) cursor.close()
        }
        return null
    }


    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    private fun isExternalStorageDocument(uri: Uri): Boolean {
        return "com.android.externalstorage.documents" == uri.getAuthority()
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    private fun isDownloadsDocument(uri: Uri): Boolean {
        return "com.android.providers.downloads.documents" == uri.getAuthority()
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    private fun isMediaDocument(uri: Uri): Boolean {
        return "com.android.providers.media.documents" == uri.getAuthority()
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is Google Photos.
     */
    private fun isGooglePhotosUri(uri: Uri): Boolean {
        return "com.google.android.apps.photos.content" == uri.getAuthority()
    }
}